package com.bhkj.websocketlibrary.ws;

import android.os.Handler;
import android.os.Message;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

public class WsCoreClient extends WebSocketClient {
    private Handler mHandler;

    public WsCoreClient(URI serverUri, Handler handler) {
        super(serverUri);
        this.mHandler = handler;
    }

    @Override
    public void onWebsocketPong(WebSocket conn, Framedata f) {
        super.onWebsocketPong(conn, f);
        LogUtils.d("心跳接收++"+f.toString());
    }

    @Override
    public void onWebsocketPing(WebSocket conn, Framedata f) {
        super.onWebsocketPing(conn, f);
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        updateStatus(WsContact.OPEN, "打开:" + handshakedata.getHttpStatusMessage() + "-" + handshakedata.getHttpStatus());
        send(NetworkUtils.getIPAddress(true)+"已经连接成功");
    }

    @Override
    public void onMessage(String message) {
        updateStatus(WsContact.RECEIVE_MSG, message);
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        updateStatus(WsContact.CLOSE_CLIENT, code + "-" + reason + "-" + remote);

//        LogUtils.d("关闭:" + code + reason + remote);
    }

    @Override
    public void onError(Exception ex) {
        updateStatus(WsContact.EXCEPTION, ex.getMessage());

        LogUtils.e(ex.getMessage());
    }

    private void updateStatus(int type, String msg) {
        Message message = new Message();
        message.what = type;
        message.obj = msg;
        if (mHandler != null) {
            mHandler.handleMessage(message);
        }
    }
}
